import { downloadTemplateApi } from "@/api/common";
import { importDownloadApi } from "@/api/managementCenter/departmentPersonnel";
import CommonHook from "@/hook/commonHook";
import FormHook from "@/hook/formHook";
import { message } from "ant-design-vue";

export default function OperationHook(state: Base.GeneraDataType) {
  const { formState, formDataRef, emit, loading } = state;
  const { resetFields } = FormHook({ formState });
  const { downloadFileByUrl } = CommonHook();
  const onFinish = () => {
    const formData = new FormData();
    formData.append("file", formState.fileList[0]);
    loading.value = true;
    return importDownloadApi(formData)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200 && !Array.isArray(data)) {
          message.success("操作成功");
          resetFields();
          formDataRef.value.clearValidate();
          emit("submit");
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const uploadRequest = (e: any) => {
    formState.fileList = [e.file];
  };
  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };
  const resetHandle = () => {
    resetFields();
    formDataRef.value.clearValidate();
    emit("update:visible", false);
  };

  // 下载模板
  const downloadTemplateHandle = () => {
    return downloadTemplateApi({ type: 10 }).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        downloadFileByUrl(data, "批量导入用户.xlsx");
      }
    });
  };
  return {
    onFinish,
    onFinishFailed,
    resetHandle,
    resetFields,
    uploadRequest,
    downloadTemplateHandle
  };
}
